#include "../inc/ClientSub.hpp"
#include <cassert>
#include <iterator>
#include <spdlog/spdlog.h>
#include <stop_token>
#include <zmq.hpp>
#include <zmq_addon.hpp>

ClientSub::ClientSub()
    : context(), subscriber(context, zmq::socket_type::sub) {}

void ClientSub::Boot(const std::string &addr) {
  subscriber.connect(addr);
  subscriber.set(zmq::sockopt::subscribe, "");
  workThread = std::jthread([this](std::stop_token token) {
    while (!token.stop_requested()) {
      std::vector<zmq::message_t> recvmsg;
      zmq::recv_result_t result =
          zmq::recv_multipart(subscriber, std::back_inserter(recvmsg));
      if (!result) {
        spdlog::warn("Failed to receive Client message");
        continue;
      }
      if (*result != 2) {
        spdlog::warn("Client message size incorret");
        continue;
      }

      std::string Head = recvmsg[0].to_string();
      if (Head == "Message") {
        if (funcMessage != nullptr)
          funcMessage(recvmsg[1].to_string());
      } else if (Head == "CameraOffline") {
        if (funcCameraOffline != nullptr)
          funcCameraOffline(recvmsg[1].to_string());
      } else if (Head == "StartShot") {
        if (funcStartShot != nullptr)
          funcStartShot(recvmsg[1].to_string());
      } else if (Head == "StopShot") {
        if (funcStopShot != nullptr)
          funcStopShot(recvmsg[1].to_string());
      } else {
        spdlog::warn("Unknow message from client {} ", recvmsg[1].to_string());
      }
    }
  });
}
